<%--
  Created by IntelliJ IDEA.
  User: Markrui
  Date: 2016/3/12
  Time: 21:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="header.jsp" %>
<div id="page-wrapper">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">我的角色</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-sm-12" >
            <button type="button" data-toggle="modal" class="btn btn-primary" onclick="showOption()" data-backdrop="static">申请职位</button>
            <br><br>
            <%--<form action="<%=request.getContextPath()%>/mng/apply/file" method="post"  enctype="multipart/form-data">--%>
                <%--<h4>测试上传文件</h4>--%>
                <%--<input type="file" name="file1">--%>
                <%--<input type="file" name="file2">--%>
                <%--<input type="submit" value="上传">--%>
            <%--</form>--%>
        </div>
        <div class="col-sm-12">
            <br>
            <table id="my_table" class="table table-hover table-bordered table-striped table-striped">
                <thead>
                <tr>
                    <td>角色</td>
                    <td>状态</td>
                    <td>审核人</td>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <!-- /.row -->
</div>

<%--modal--%>
<div id="apply_modal" class="modal fade">
    <div class="modal-dialog modal-lg" >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">申请认证</h4>
            </div>
            <div class="modal-body">
                <div class="row">

                    <div class="form-group">
                        <form id="apply_form" >
                            <div class="col-sm-12">
                                <div class="col-sm-1"></div>
                                <div class="col-sm-3" style="padding-top:5px">
                                    <label for="groupId" class="control-label">申请职位</label>
                                </div>

                                <div class="col-sm-6">
                                    <select class="form-control" id="groupId" name="groupId">

                                    </select>
                                </div>
                            </div>

                                    <input id="fileUrls"  class="form-control" type="hidden" />


                            <div id="add"></div>
                            <%--<div class="col-sm-12">--%>
                                <%--<br>--%>
                                <%--<div class="col-sm-1"></div>--%>
                                <%--<div class="col-sm-3" style="padding-top:5px">--%>
                                    <%--<label for="date" class="control-label">证书日期：</label>--%>
                                <%--</div>--%>
                                <%--<div class="col-sm-6">--%>
                                    <%--<input id="date" name="date" class="form-control" />--%>
                                <%--</div>--%>
                            <%--</div>--%>
                        </form>
                    </div>

                    <div class="col-sm-12" id="uploaderContent">
                        <br>
                        <div class="col-sm-1"></div>
                        <div class="col-sm-3" style="padding-top:5px">
                            <label for="groupId" class="control-label">请上传文件：</label>
                        </div>
                        <div  class="col-sm-6">
                            <div id="uploader" class="wu-example">
                                <!--用来存放文件信息-->
                                <div id="thelist" class="uploader-list"></div>
                                <div class="btns" id="uploadButton">
                                    <div id="picker">选择文件</div>
                                    <button id="ctlBtn" class="btn btn-default">开始上传</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button id="apply_submit_btn" data-dismiss="modal" class="btn btn-primary" onclick="submit(this)">提交申请</button>
                <button class="btn btn-default" data-dismiss="modal">返回</button>
            </div>
        </div>
    </div>
</div>
<!-- /#page-wrapper -->
<%@include file="footer.jsp" %>
<script>

    var hasFile = false;
    var clickedToUpload = false;

    var editor = {
        name : "",
        control : ""
    };
    var editorList = [];
    $(document).ready(function() {
        loadTable();
        loadOption();
        CKEDITOR.disableAutoInline = true;
    });


    function showOption(){
        loadOption();
        $('#apply_modal').modal('show')
    }


    var table;
    function loadTable(){
        $.ajax({
            url: rootUrl+'mng/user/group',
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            table = $('#my_table').DataTable({
                "bProcessing": true,
                "bDestroy": true,
                "sPaginationType" : "full_numbers",
                "oLanguage" : {
                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                    "sZeroRecords": "抱歉， 没有找到",
                    "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                    "sInfoEmpty": "没有数据",
                    "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                    "sZeroRecords": "没有检索到数据",
                    "sSearch": "搜索: &nbsp",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "前一页",
                        "sNext": "后一页",
                        "sLast": "尾页"
                    }
                },
                "data":data.data.groups,
                "columns": [
                    { "data": 'groupEntity.name' },
                    { "data": 'status' },
                    { "data": 'checkerName' }
                ],
                "columnDefs": [
                    {
                        "targets": 1,
                        "render": function (data, type, row, table) {
                            return getStatus(data);
//                            console.log(data);
//                            return data[0].label;
                        }
                    }]
            });
        });
    }

    function getStatus(statusNum){
        switch (statusNum){
            case 0:
                return "待审核";
            case 1:
                return "审核通过";
            case 2:
                return "未通过";
        }
    }

    function loadOption(){

        hasFile = false;
        clickedToUpload = false;
        $("#fileUrls").attr("name",-1);


        $("#uploaderContent").hide();
        $("#uploadUrls").hide();

        $.ajax({
            url: rootUrl+'mng/group',
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            var groups = data.data.groups;
            var html = "";
            for(var i = 0; i < groups.length; i++){
                html += '<option value="'+groups[i].groupId+'">'+groups[i].name+'</option>';
                if(i != 0){
                    continue;
                }

                console.log(groups[0].groupForms);
                $("#add").html("");
                for(var j = 0; j < groups[0].groupForms.length; j++){
                    var addHtml = "";
                    addHtml += '<div class="col-sm-12">'+
                            '<br>'+
                            '<div class="col-sm-1"></div>'+
                            '<div class="col-sm-3" style="padding-top:5px">'+
                            '<label for="name" class="control-label">'+groups[0].groupForms[j].label+'</label>'+
                            '</div>'+
                            '<div class="col-sm-6">';
                    var type = "";
                    if(groups[0].groupForms[j].type == 0){
                        type = '<input id="name" name="'+groups[0].groupForms[j].groupFormId+'"  type="text" class="form-control" />';
                    }else if(groups[0].groupForms[j].type == 1){
                        type = '<select class="form-control" name="'+groups[0].groupForms[j].groupFormId+'">';
                        var option = groups[0].groupForms[j].valueTemplate.split("#");
                        for(var k = 0; k < option.length; k++){
                            if(option[k] != ""){
                                type += '<option value="'+option[k]+'" class="form-control">'+option[k]+'</option>';
                            }
                        }
                        type += '</select>';
                    }else if(groups[0].groupForms[j].type == 2){
                        hasFile = true;
                        $("#uploaderContent").show();
                        $("#uploadUrls").show();
                        // 表单有 文件
                        $("#fileUrls").attr("name",groups[0].groupForms[j].groupFormId);
                        type = '<input id="files" disabled="true" value="请在下方选择上传文件" type="text" class="form-control" name="'+groups[0].groupForms[j].groupFormId+'" />';
                    }else if(groups[0].groupForms[j].type == 3){
                        type = '<textarea id="name" class="form-control" name="'+groups[0].groupForms[j].groupFormId+'" /></textarea>';
                    }else if(groups[0].groupForms[j].type == 4){
                        type = '<textarea id="name" class="form-control" name="'+groups[0].groupForms[j].groupFormId+'" /></textarea>';
                    }
                    addHtml += type+
                            '</div>'+
                            '</div>';
                    $("#add").append(addHtml);
                    if(groups[0].groupForms[j].type == 4){
                        var e = CKEDITOR.replace(groupForms[j].groupFormId.toString(), { toolbar:'Basic', height:270 });
                        editor.name = groupForms[j].groupFormId;
                        editor.control = e;
                        editorList.push(editor);
                    }
                }
            }

            $("#groupId").html(html);
        });
    }

    $("#groupId").on( 'change', function () {
        hasFile = false;
        clickedToUpload = false;

        $("#fileUrls").attr("name",-1);


        var groupId = $(this).val();
        $.ajax({
            url: rootUrl+'mng/group/'+groupId,
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            var groupForms = data.data.group.groupForms;
            console.log(groupForms);
            $("#add").html("");
            for(var j = 0; j < groupForms.length; j++){
                var addHtml = "";
                addHtml += '<div class="col-sm-12">'+
                        '<br>'+
                        '<div class="col-sm-1"></div>'+
                        '<div class="col-sm-3" style="padding-top:5px">'+
                        '<label for="name" class="control-label">'+groupForms[j].label+'</label>'+
                        '</div>'+
                        '<div class="col-sm-6">';
                var type = "";
                if(groupForms[j].type == 0){
                    type = '<input id="name"  type="text" class="form-control" name="'+groupForms[j].groupFormId+'" />';
                }else if(groupForms[j].type == 1){
                    type = '<select class="form-control" name="'+groupForms[j].groupFormId+'">';
                    var option = groupForms[j].valueTemplate.split("#");
                    for(var k = 0; k < option.length; k++){
                        if(option[k] != ""){
                            type += '<option value="'+option[k]+'" class="form-control">'+option[k]+'</option>';
                        }
                    }
                    type += '</select>';
                }else if(groupForms[j].type == 2){
                    hasFile = true;
                    $("#uploaderContent").show();
                    $("#uploadUrls").show();
                    $("#fileUrls").attr("name",groupForms[j].groupFormId);
                    type = '<input id="files" disabled="true" value="请在下方选择上传文件"  type="text"  class="form-control" name="'+groupForms[j].groupFormId+'" />';
                }else if(groupForms[j].type == 3){
                    type = '<textarea id="name" class="form-control" name="'+groupForms[j].groupFormId+'" /></textarea>';
                }else if(groupForms[j].type == 4){
                    type = '<textarea id="name" class="form-control" name="'+groupForms[j].groupFormId+'" /></textarea>';
                }
                addHtml += type+
                        '</div>'+
                        '</div>';
                $("#add").append(addHtml);
                if(groupForms[j].type == 4){
                    var e = CKEDITOR.replace(groupForms[j].groupFormId.toString(), { toolbar:'Basic', height:270 });
                    editor.name = groupForms[j].groupFormId;
                    editor.control = e;
                    editorList.push(editor);
                }
            }
        });
    });

    function submit(button){

        console.log("当前的状态是：",hasFile + "" + clickedToUpload);
        if(hasFile && !clickedToUpload){
            console.log("请先点击上传按钮，上传文件",hasFile + "" + clickedToUpload);
            alert("请先点击上传按钮，上传文件");
            return;
        }

        var newApply = {
            groupId:"",
            userGroupFormValues:[]
        };
        var param = $('#apply_form').serializeArray();
        console.log("序列化的 parameter：" ,param);
        for (var i = 0; i < param.length; i++)
            if(param[i].name == "groupId"){
                newApply.groupId = param[i].value;
            }else{
                var userGroupFormValue = {
                    groupFormId:"",
                    value:""
                };

                userGroupFormValue.groupFormId = param[i].name;
                userGroupFormValue.value = param[i].value;


                for(var index in editorList){
                    if(editorList[index].name == param[i].name){
                        userGroupFormValue.value = editorList[index].control.getData();
                    }
                }
                newApply.userGroupFormValues.push(userGroupFormValue);
            }

        console.log(JSON.stringify(newApply));
        $.ajax({
            url: rootUrl+'mng/apply',
            contentType:"application/json",
            type: 'post',
            dataType: 'json',
            data:JSON.stringify(newApply)
        })
        .success(function(data){
           loadTable();
           button.dataDismiss = "modal";
            alert(data.message);
           $("#apply_submit_btn").dataDismiss = "modal";
            $("#apply_submit_btn").modal('hide');

           clickedToUpload = false;
           hasFile=false;

            console.log(data);
        }).error(function(){
              alert("添加失败");
        });


    }




    var BASE_URL = "../../webupload";
    // 文件上传
    jQuery(function() {
        var $ = jQuery,
                $list = $('#thelist'),
                $btn = $('#ctlBtn'),
                state = 'pending',
                uploader;

        uploader = WebUploader.create({

            // 不压缩image
            resize: false,

            // swf文件路径
            swf: BASE_URL + '/js/Uploader.swf',

            // 文件接收服务端。
            server: rootUrl + "mng/apply/file",

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker'
        });

        // 当有文件添加进来的时候
        uploader.on( 'fileQueued', function( file ) {
            $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info" id="title">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>' );
        });

        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                    $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css( 'width', percentage * 100 + '%' );
        });

        uploader.on( 'uploadSuccess', function( file, response) {
            $( '#'+file.id ).find('p.state').text('已上传');


            var data = response.data.urls;
            console.log("服务器返回的数据的是：" , data);

            initData(data);
            clickedToUpload = true;

            $("#videoInfo").removeClass("am-fade")

        });

        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });

        uploader.on( 'uploadComplete', function( file ) {
            // 隐藏进度条
//      $( '#'+file.id ).find('.progress').fadeOut();
            // 隐藏 button
            $("#uploadButton").hide();
//      $("#uploadButton").addClass("am-fade");
            $("#title").hide();
        });

        uploader.on( 'all', function( type ) {
            if ( type === 'startUpload' ) {
                state = 'uploading';
            } else if ( type === 'stopUpload' ) {
                state = 'paused';
            } else if ( type === 'uploadFinished' ) {
                state = 'done';
            }

            if ( state === 'uploading' ) {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        $btn.on( 'click', function() {
            if ( state === 'uploading' ) {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });
    });


    function initData(data){
       var urls = "";
       if(data != null && data.length > 0){
           for(var i = 0; i < data.length;i++){
               urls += data[i];
               if(i < data.length-1){
                   urls += ";";
               }
           }
       }
        $("#fileUrls").val(urls);
    }



</script>
<script type="text/javascript" src="../../ckeditor/ckeditor.js"></script>